package com.gsnd.gsnd22estore.web.controller;

import com.alipay.api.domain.CreditQuotaDetail;
import com.gsnd.gsnd22estore.domain.EsAddress;
import com.gsnd.gsnd22estore.result.Result;
import com.gsnd.gsnd22estore.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping
    public Result<List<EsAddress>> findAll(HttpServletRequest request){
        return Result.success(addressService.getAllAddressByUserId(Integer.parseInt((String) request.getAttribute("userId"))));
    }

    @PostMapping
    public Result<String> addAddress( EsAddress address){
        addressService.createAddress(address);
        return Result.success("新增收货地址成功");
    }
    @PutMapping
    public Result editAddress(@RequestBody EsAddress address)
    {
        addressService.editAddressInfo(address);
        return Result.success("修改收货地址成功");
    }

    @DeleteMapping
    public Result removeAddress(Integer id)
    {
        addressService.removeAddressById(id);
        return Result.success("删除收货地址成功");
    }

    @PutMapping("/cancelDefault/{addressId}")
    public Result<String> cancelDefaultAddress(HttpServletRequest request,
                                               @PathVariable Integer addressId){

        Integer userId = Integer.parseInt((String) request.getAttribute("userId"));
        addressService.changeDefaultAddress(null,userId);

        return Result.success("用户取消默认地址");
    }

    @PutMapping("/setDefault/{addressId}")
    public Result<String> setDefaultAddress(HttpServletRequest request,
                                            @PathVariable Integer addressId){
        Integer userId = Integer.parseInt((String) request.getAttribute("userId"));
        addressService.changeDefaultAddress(addressId,userId);
        return Result.success("用户设置默认地址成功");
    }
}
